import { defineComponent, computed, VNodeChild, PropType } from 'vue'
import { Value } from './interface'

import Tooltip from '../tooltip'
import MenuItemContent from './MenuItemContent'
import { useMenu } from './utils'

export const menuItemProps = {
  label: [String, Object] as PropType<string | VNodeChild>,
  value: [String, Number] as PropType<Value>,
  icon: [Object, Function] as PropType<VNodeChild | (() => VNodeChild)>,
  disabled: Boolean
}

export default defineComponent({
  name: 'x-menu-item',
  props: menuItemProps,
  setup(props) {
    const { paddingLeftRef, menuContext, disabledRef, isActiveRef, isRoot } = useMenu(props)

    const prefixCls = 'x-menu-item'
    const selectedRef = computed(() => menuContext.valueRef.value === props.value)

    function onClick() {
      menuContext.onSelect(props)
    }

    return () => {
      const cls = {
        [prefixCls]: true,
        [`${prefixCls}-selected`]: selectedRef.value,
        [`${prefixCls}-disabled`]: disabledRef.value
      }

      return (
        <Tooltip disabled={!isRoot || disabledRef.value || !menuContext.collapsedRef.value} placement='right' title={props.label}>
          <div class={cls} role='menuitem' aria-disabled={disabledRef.value}>
            <MenuItemContent {...props} style={`paddingLeft:${paddingLeftRef.value}px`} active={isActiveRef.value} onClick={onClick} />
          </div>
        </Tooltip>
      )
    }
  }
})
